<?php

namespace app\admin\controller\api;

use app\common\model;

/**
 * 消息推送
 * @internal
 */
class Socket extends Api
{
    protected $noNeedLogin = ['publish', 'check'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 推送消息
     *
     * @param device_ids array 设备key id
     * @param content json 消息内容
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function publish()
    {
        $device_ids = $this->request->request('device_ids/a');
        $content = $this->request->request('content');

        if (!is_array($device_ids)) {
            $this->error('参数有误');
        }

        $device_keys = model\DeviceKey::whereIn('id', $device_ids)->column('key');

        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://socket.uxuj.cn:2123', $errno, $errmsg, 1);
        // 推送的数据
        $data = array(
            'type' => 'publish',
            'content' => json_decode($content, true),
            'to' => $device_keys
        );

        //echo json_encode($data);die;

        // 发送数据，注意2123端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($data) . "\n");
        // 读取推送结果
        $ret = fread($client, 8192);
        $ret = str_replace(PHP_EOL, '', $ret);

        $this->success('', $ret);
    }

    /*public function publish()
    {
        $device_ids = $this->request->request('device_ids/a');
        $content = $this->request->request('content');

        if (!is_array($device_ids)) {
            $this->error('参数有误');
        }

        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://socket.uxuj.cn:2123', $errno, $errmsg, 1);
        // 推送的数据
        $data = array(
            'type' => 'publish',
            'content' => json_decode($content, true),
            'to' => $device_ids
        );

        // 发送数据，注意2123端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($data) . "\n");
        // 读取推送结果
        $ret = fread($client, 8192);
        $ret = str_replace(PHP_EOL, '', $ret);
        $this->success('', $ret);
    }*/

    public function check()
    {
        $ids = $this->request->request('ids/a');

        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://socket.uxuj.cn:2123', $errno, $errmsg, 1);
        // 推送的数据
        $data = array(
            'type' => 'check',
            'content' => $ids,
        );

        // 发送数据，注意2123端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($data) . "\n");
        // 读取推送结果
        $ret = fread($client, 8192);
        $ret = str_replace(PHP_EOL, '', $ret);

        header('Content-type: application/json; charset=UTF-8');
        echo $ret;die;
    }


}